package org.ph.share.lock.test.thread2;

import lombok.extern.slf4j.Slf4j;

/**
 * 执行三个线程顺序输出abcabc
 * Use Wait And Notify
 *
 * @author Hush.
 * @since 2023/5/18 12:53
 */
@Slf4j
public class Thread16 {
    public static void main(String[] args) throws InterruptedException {

        WaitNotify waitNotify = new WaitNotify(2);
        Thread thread1 = new Thread(() -> waitNotify.print(1, "a", 2), "t1");
        Thread thread2 = new Thread(() -> waitNotify.print(2, "b", 3), "t2");
        Thread thread3 = new Thread(() -> waitNotify.print(3, "c", 1), "t3");
        thread1.start();
        thread2.start();
        thread3.start();

    }
}

@Slf4j
class WaitNotify {
    /**
     * 标记
     */
    private int flag;
    /**
     * 循环次数
     */
    private final int cycles;

    public WaitNotify(int cycles) {
        this.cycles = cycles;
        this.flag = 1;
    }

    /**
     * 打印
     *
     * @param waitFlag 等待标记
     * @param mess     消息
     * @param nextFlag 下个标记
     */
    public void print(int waitFlag, String mess, int nextFlag) {
        for (int i = 0; i < cycles; i++) {
            synchronized (this) {
                // 当前flag不与线程传来的参数一致，进入等待
                while (this.flag != waitFlag) {
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                this.flag = nextFlag;
                log.info("mess:{}", mess);
                notifyAll();
            }
        }
    }
}